package com.ruoyi.wxApi;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.TencentCosUtils;
import com.ruoyi.lock.domain.*;
import com.ruoyi.lock.mapper.ACellMapper;
import com.ruoyi.lock.mapper.ATenantuserMapper;
import com.ruoyi.lock.service.*;
import com.ruoyi.locksApi.domain.ATask;
import com.ruoyi.locksApi.domain.dto.PhoneLoginDTO;
import com.ruoyi.locksApi.mapper.ATaskMapper;
import com.ruoyi.locksApi.service.PhoneLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/v1")
@Anonymous
public class PhoneLoginController {

    private static final Logger log = LoggerFactory.getLogger(PhoneLoginController.class);

    @Autowired
    private PhoneLoginService phoneLoginService;
    
    @Autowired
    private ITenantInfoService tenantInfoService;
    
    @Autowired
    private ITContractService contractService;

    @Autowired
    private IACheckaInService aCheckaInService;

    @Autowired
    private ACellMapper aCellMapper;

    @Autowired
    private IAOpenlockService aOpenlockService;

    @Autowired
    private ATenantuserMapper tenantuserMapper;

    @Autowired
    private IATenantkeyService aTenantkeyService;

    @Autowired
    private ATaskMapper taskMapper;

    @Autowired
    private IATypeService aTypeService;

    @Autowired
    private ISysSettingService sysSettingService;

    @Autowired
    private IAProblemsService problemsService;

    /**
     * 发送手机验证码
     */
    @Anonymous
    @PostMapping("/login/phoneCheck")
    public AjaxResult phoneCheck(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        if (StringUtils.isEmpty(phone)) {
            return AjaxResult.error("手机号不能为空");
        }

        try {
            boolean success = phoneLoginService.sendVerificationCode(phone);
            if (success) {
                return AjaxResult.success("验证码发送成功");
            } else {
                return AjaxResult.error("验证码发送失败");
            }
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("发送验证码失败", e);
            return AjaxResult.error("验证码发送失败，请稍后重试");
        }
    }

    /**
     * 手机号登录
     */
    @Anonymous
    @PostMapping("/login/phone")
    public AjaxResult phoneLogin(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        String code = params.get("code");
        
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            return AjaxResult.error("手机号和验证码不能为空");
        }

        try {
            // 验证验证码
            boolean isValid = phoneLoginService.verifyCode(phone, code);
            if (!isValid) {
                return AjaxResult.error("验证码错误或已过期");
            }

            // 执行登录
            return phoneLoginService.phoneLogin(new PhoneLoginDTO(phone, code));
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("手机号登录失败", e);
            return AjaxResult.error("登录失败，请稍后重试");
        }
    }
    
    /**
     * 根据MAC地址查询门锁钥匙
     *
     * @param mac 门锁MAC地址
     * @param userInfo 用户信息
     * @return 门锁钥匙列表
     */
    @GetMapping("/device/keys")
    public AjaxResult getDeviceKeys(@RequestParam("mac") String mac, @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        return phoneLoginService.getDeviceKeys(mac, userId);
    }

    /**
     * 根据用户ID查询租户基本信息
     *
     * @param userId 租户ID
     * @return 租户基本信息
     */
    @GetMapping("/user/info/{userId}")
    @Anonymous
    public AjaxResult getUserInfoById(@PathVariable("userId") Long userId) {
        return tenantInfoService.getTenantInfoById(userId);
    }

    /**
     * 获取当前登录租户的基本信息
     *
     * @param userInfo 用户信息
     * @return 租户基本信息
     */
    @GetMapping("/user/info")
    public AjaxResult getCurrentUserInfo(@RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        return tenantInfoService.getTenantInfoById(userId);
    }

    /**
     * 获取当前登录租户的基本信息（精简版）
     *
     * @param userInfo 用户信息
     * @return 租户基本信息（仅包含基本字段）
     */
    @GetMapping("/user/basic-info")
    public AjaxResult getCurrentUserBasicInfo(@RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        return tenantInfoService.getTenantBasicInfoById(userId);
    }

    @GetMapping("/device/info")
    public AjaxResult getDeviceInfo(@RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long homeId = (Long) userInfo.get("homeId");
        return phoneLoginService.getDeviceInfo(homeId);
    }
    
    /**
     * 提交故障报告
     *
     * @param data 故障报告数据
     * @param userInfo 用户信息
     * @return 操作结果
     */
    @PostMapping("/fault/report")
    public AjaxResult submitFaultReport(@RequestBody Map<String, Object> data, @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        Long homeId = userInfo.containsKey("homeId") ? Long.valueOf(userInfo.get("homeId").toString()) : null;
        
        // 从请求体中获取故障信息
        String waringType = data.containsKey("waringType") ? data.get("waringType").toString() : "1";
        String remark = data.containsKey("remark") ? data.get("remark").toString() : null;
        String remark2 = data.containsKey("remark2") ? data.get("remark2").toString() : null;
        String img = data.containsKey("img") ? data.get("img").toString() : null;
        
        // 从请求体中获取MAC地址，如果没有则留给服务层根据homeId查询
        String mac = data.containsKey("mac") ? data.get("mac").toString() : null;
        
        return phoneLoginService.submitFaultReport(waringType, remark, remark2, img, userId, mac, homeId);
    }
    
    /**
     * 查询用户的故障报告列表
     *
     * @param userInfo 用户信息
     * @return 故障报告列表
     */
    @GetMapping("/fault/report/list")
    public AjaxResult getFaultReportList(@RequestParam(value = "pageNum", required = false) Integer pageNum,
                                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                        @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        return phoneLoginService.getFaultReportList(userId, pageNum, pageSize);
    }
    
    /**
     * 获取故障报告详情
     *
     * @param id 故障报告ID
     * @param userInfo 用户信息
     * @return 故障报告详情
     */
    @GetMapping("/fault/report/{id}")
    public AjaxResult getFaultReportDetail(@PathVariable("id") Long id, @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        return phoneLoginService.getFaultReportDetail(id, userId);
    }
    
    /**
     * 修改故障报告
     *
     * @param id 故障报告ID
     * @param data 故障报告数据
     * @param userInfo 用户信息
     * @return 操作结果
     */
    @PutMapping("/fault/report/{id}")
    public AjaxResult updateFaultReport(@PathVariable("id") Long id, 
                                      @RequestBody Map<String, Object> data, 
                                      @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        
        // 从请求体中获取故障信息
        String waringType = data.containsKey("waringType") ? data.get("waringType").toString() : "1";
        String remark = data.containsKey("remark") ? data.get("remark").toString() : null;
        String remark2 = data.containsKey("remark2") ? data.get("remark2").toString() : null;
        String img = data.containsKey("img") ? data.get("img").toString() : null;
        
        return phoneLoginService.updateFaultReport(id, waringType, remark, remark2, img, userId);
    }
    
    /**
     * 获取当前用户有效合同信息
     *
     * @param userInfo 用户信息
     * @return 合同信息
     */
    @GetMapping("/contract/info")
    public AjaxResult getCurrentUserContract(@RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        
        // 查询当前用户的有效合同
        TContract query = new TContract();
        query.setTenantId(userId);
        List<TContract> contracts = contractService.selectTContractList(query);
        
        if (contracts == null || contracts.isEmpty()) {
            return AjaxResult.success("暂无有效合同", null);
        }
        // 转换为前端所需格式
        return AjaxResult.success(contracts);
    }
    
    /**
     * 获取当前用户小区公告
     *
     * @param userInfo 用户信息
     * @return 公告列表
     */
    @GetMapping("/notification/list")
    public AjaxResult getNotificationList(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "3") Integer pageSize,
            @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        // 从请求头中获取住宅ID
        Long homeId = userInfo.containsKey("homeId") ? Long.valueOf(userInfo.get("homeId").toString()) : null;
        
        if (homeId == null) {
            return AjaxResult.error("未获取到住宅信息");
        }
        
        // 根据住宅ID直接查询小区公告，支持分页
        List<Map<String, Object>> notifications = phoneLoginService.getNotificationsByHomeId(homeId);
        
        // 如果没有数据，返回空数组
        if (notifications == null || notifications.isEmpty()) {
            return AjaxResult.success(new ArrayList<>());
        }
        
        // 手动处理分页
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, notifications.size());
        
        // 防止越界
        if (startIndex >= notifications.size()) {
            return AjaxResult.success(new ArrayList<>());
        }
        
        // 返回指定页的数据
        return AjaxResult.success(notifications.subList(startIndex, endIndex));
    }
    
    /**
     * 获取公告详情
     *
     * @param id 公告ID
     * @return 公告详情
     */
    @GetMapping("/notification/detail/{id}")
    public AjaxResult getNotificationDetail(@PathVariable("id") String id) {
        // 根据公告ID查询详情
        Map<String, Object> detail = phoneLoginService.getNotificationDetail(id);
        
        if (detail != null) {
            return AjaxResult.success(detail);
        } else {
            return AjaxResult.error("未找到公告信息");
        }
    }

    /**
     * 提交打卡记录
     *
     * @param data 打卡数据，可包含位置、经纬度等信息
     * @param userInfo 用户信息
     * @return 操作结果
     */
    @PostMapping("/checkin/submit")
    public AjaxResult submitCheckin(@RequestBody(required = false) Map<String, Object> data, 
                                  @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        Long homeId = userInfo.containsKey("homeId") ? Long.valueOf(userInfo.get("homeId").toString()) : null;
        
        if (homeId == null) {
            return AjaxResult.error("未获取到住宅信息，打卡失败");
        }
        
        // 检查今日是否已打卡
        ACheckaIn query = new ACheckaIn();
        query.setTenantId(userId);
        query.setHomeId(homeId.toString());
        
        // 查询用户当天的打卡记录
        List<ACheckaIn> todayCheckins = aCheckaInService.checkAInList(query);
        
        // 过滤出今天的打卡记录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String today = dateFormat.format(new Date());
        
        boolean alreadyCheckedIn = todayCheckins.stream()
            .anyMatch(checkin -> dateFormat.format(checkin.getCheckinDate()).equals(today));
        
        if (alreadyCheckedIn) {
            return AjaxResult.error("今日已打卡，无需重复打卡");
        }
        
        // 获取打卡信息
        String location = data != null && data.containsKey("location") ? data.get("location").toString() : "默认位置";
        BigDecimal longitude = data != null && data.containsKey("longitude") ? new BigDecimal(data.get("longitude").toString()) : null;
        BigDecimal latitude = data != null && data.containsKey("latitude") ? new BigDecimal(data.get("latitude").toString()) : null;
        
        // 创建打卡记录
        ACheckaIn checkin = new ACheckaIn();
        checkin.setTenantId(userId);
        checkin.setHomeId(homeId.toString());
        checkin.setCheckinDate(new Date());
        checkin.setLocation(location);
        checkin.setLongitude(longitude);
        checkin.setLatitude(latitude);
        checkin.setStatus(1L); // 1表示打卡成功
        
        // 保存打卡记录
        int result = aCheckaInService.insertACheckaIn(checkin);
        
        if (result > 0) {
            return AjaxResult.success("打卡成功");
        } else {
            return AjaxResult.error("打卡失败，请稍后重试");
        }
    }

    /**
     * 获取打卡地点信息
     */
    @GetMapping("/checkin/location")
    public AjaxResult getCheckinLocation(@RequestAttribute("userInfo") Map<String, Object> userInfo) {
        // 直接获取cellId
        if (!userInfo.containsKey("cellId") || userInfo.get("cellId") == null) {
            return AjaxResult.error("未找到小区信息");
        }
        
        Long cellId = Long.valueOf(userInfo.get("cellId").toString());
        
        // 直接通过cellId获取小区信息
        ACell cell = aCellMapper.selectACellById(cellId);
        if (cell == null) {
            return AjaxResult.error("未找到打卡地点信息");
        }
        
        // 构建返回结果
        Map<String, Object> locationInfo = new HashMap<>();
        locationInfo.put("latitude", cell.getLatitude());
        locationInfo.put("longitude", cell.getLongitude());
        locationInfo.put("address", cell.getAddress());
        locationInfo.put("cellName", cell.getName());
        
        return AjaxResult.success(locationInfo);
    }

    /**
     * 查询用户打卡记录
     *
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @param dateStr 搜索日期（可选，格式：yyyy-MM-dd）
     * @param userInfo 用户信息
     * @return 打卡记录列表
     */
    @GetMapping("/checkin/records")
    public AjaxResult getCheckinRecords(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "date", required = false) String dateStr,
            @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        // 从请求头中获取住宅ID
        Long homeId = userInfo.containsKey("homeId") ? Long.valueOf(userInfo.get("homeId").toString()) : null;
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        
        if (homeId == null) {
            return AjaxResult.error("未获取到住宅信息");
        }
        
        // 构建查询条件
        ACheckaIn query = new ACheckaIn();
        query.setTenantId(userId);
        query.setHomeId(homeId.toString());
        
        // 如果指定了日期，添加日期条件
        if (dateStr != null && !dateStr.isEmpty()) {
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date = format.parse(dateStr);
                query.setCheckinDate(date); // 设置查询日期
            } catch (Exception e) {
                return AjaxResult.error("日期格式不正确，请使用yyyy-MM-dd格式");
            }
        }
        
        // 查询打卡记录
        List<ACheckaIn> checkins = aCheckaInService.checkAInList(query);
        
        // 如果没有数据，返回空数组
        if (checkins == null || checkins.isEmpty()) {
            return AjaxResult.success(new ArrayList<>());
        }
        
        // 按打卡日期降序排序（最新的记录在前面）
        checkins.sort((a, b) -> b.getCheckinDate().compareTo(a.getCheckinDate()));
        
        // 手动处理分页
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, checkins.size());
        
        // 防止越界
        if (startIndex >= checkins.size()) {
            return AjaxResult.success(new ArrayList<>());
        }
        
        // 返回指定页的数据
        List<ACheckaIn> pagedCheckins = checkins.subList(startIndex, endIndex);
        
        // 转换为前端需要的格式
        List<Map<String, Object>> result = new ArrayList<>();
        SimpleDateFormat displayFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        for (ACheckaIn checkin : pagedCheckins) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", checkin.getId());
            item.put("checkinDate", displayFormat.format(checkin.getCheckinDate()));
            item.put("location", checkin.getLocation());
            item.put("status", checkin.getStatus());
            item.put("latitude", checkin.getLatitude());
            item.put("longitude", checkin.getLongitude());
            
            result.add(item);
        }
        
        // 构建分页信息
        Map<String, Object> pageInfo = new HashMap<>();
        pageInfo.put("total", checkins.size());
        pageInfo.put("pageNum", pageNum);
        pageInfo.put("pageSize", pageSize);
        pageInfo.put("records", result);
        
        return AjaxResult.success(pageInfo);
    }

    /**
     * 获取某月的打卡记录日期列表
     *
     * @param yearMonth 年月（格式：yyyy-MM）
     * @param userInfo 用户信息
     * @return 打卡日期列表
     */
    @GetMapping("/checkin/month-stats")
    public AjaxResult getCheckinMonthStats(
            @RequestParam(value = "yearMonth", required = true) String yearMonth,
            @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        // 从请求头中获取住宅ID
        Long homeId = userInfo.containsKey("homeId") ? Long.valueOf(userInfo.get("homeId").toString()) : null;
        Long userId = Long.valueOf(userInfo.get("userId").toString());
        
        if (homeId == null) {
            return AjaxResult.error("未获取到住宅信息");
        }
        
        // 验证yearMonth格式
        if (!yearMonth.matches("\\d{4}-\\d{2}")) {
            return AjaxResult.error("日期格式不正确，请使用yyyy-MM格式");
        }
        
        // 获取打卡日期列表
        List<Map<String, Object>> checkinDates = aCheckaInService.getCheckinDatesByMonth(userId, homeId.toString(), yearMonth);
        
        return AjaxResult.success(checkinDates);
    }

    /**
     * 获取开门记录列表
     *
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @param dateStr 日期（可选，格式：yyyy-MM-dd）
     * @param userInfo 用户信息
     * @return 开门记录列表
     */
    @GetMapping("/door/records")
    public AjaxResult getDoorRecords(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "date", required = false) String dateStr,
            @RequestAttribute("userInfo") Map<String, Object> userInfo) {
        // 从请求头中获取住宅ID
        Long homeId = userInfo.containsKey("homeId") ? Long.valueOf(userInfo.get("homeId").toString()) : null;
        
        if (homeId == null) {
            return AjaxResult.error("未获取到住宅信息");
        }
        
        // 调用服务层方法查询开门记录
        try {
            // 调用PhoneLoginService的方法获取开门记录
            List<Map<String, Object>> records = phoneLoginService.getOpenLockRecords(homeId, dateStr);
            
            // 查询失败或无数据，返回空数组
            if (records == null || records.isEmpty()) {
                return AjaxResult.success(new ArrayList<>());
            }
            
            // 手动处理分页
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, records.size());
            
            // 防止越界
            if (startIndex >= records.size()) {
                return AjaxResult.success(new ArrayList<>());
            }
            
            // 返回指定页的数据
            List<Map<String, Object>> pagedRecords = records.subList(startIndex, endIndex);
            
            // 转换为前端需要的格式
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (Map<String, Object> record : pagedRecords) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", record.get("id"));
                item.put("lockTime", record.get("create_time"));
                item.put("type", record.get("type"));
                item.put("username", record.get("username")); // 用户名
                item.put("phone", record.get("phone")); // 电话
                
                // 开门方式：1-密码开门，2-卡片开门，3-指纹开门，4-蓝牙开门，0-其他
                String type = record.get("type") != null ? record.get("type").toString() : "0";
                String openType = "";
                switch (type) {
                    case "1": openType = "密码开门"; break;
                    case "2": openType = "卡片开门"; break;
                    case "3": openType = "指纹开门"; break;
                    case "4": openType = "蓝牙开门"; break;
                    default: openType = "其他方式"; break;
                }
                item.put("openType", openType);
                
                result.add(item);
            }
            
            // 构建分页信息
            Map<String, Object> pageInfo = new HashMap<>();
            pageInfo.put("total", records.size());
            pageInfo.put("pageNum", pageNum);
            pageInfo.put("pageSize", pageSize);
            pageInfo.put("records", result);
            
            return AjaxResult.success(pageInfo);
            
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询开门记录失败: " + e.getMessage());
        }
    }

    /**
     * 验证钥匙有效性
     *
     * @param keyId 钥匙ID
     * @return 验证结果
     */
    @GetMapping("/key/verify/{keyId}")
    public AjaxResult verifyKey(@PathVariable("keyId") Long keyId) {
        try {
            // 查询钥匙信息
            ATenantkey key = aTenantkeyService.selectATenantkeyById(keyId);
            
            if (key == null) {
                return AjaxResult.error("钥匙不存在");
            }
            
            // 检查是否在有效期内
            Date now = new Date();
            if (now.before(key.getStartTime()) || now.after(key.getEndTime())) {
                return AjaxResult.error("钥匙不在有效期内");
            }
            
            // 检查是否有pwdId
            if (key.getPwdId() == null) {
                return AjaxResult.error("钥匙未分配密码ID");
            }
            
            // 检查钥匙状态
            if (key.getIsItAvailable() != null && key.getIsItAvailable() == 1) {
                return AjaxResult.error("钥匙已被冻结");
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("keyId", key.getId());
            result.put("pwdId", key.getPwdId());
            result.put("startTime", key.getStartTime());
            result.put("endTime", key.getEndTime());
            result.put("type", key.getType());
            
            return AjaxResult.success("钥匙验证通过", result);
            
        } catch (Exception e) {
            log.error("验证钥匙失败", e);
            return AjaxResult.error("验证钥匙失败：" + e.getMessage());
        }
    }

    /**
     * 修改钥匙密码
     *
     * @param keyId 钥匙ID
     * @param newPassword 新密码
     * @return 操作结果
     */
    @PostMapping("/key/update-password")
    public AjaxResult updateKeyPassword(@RequestParam("keyId") String keyId, @RequestParam("newPassword") String newPassword) {
        try {
            // 查询钥匙信息
            ATenantkey key = aTenantkeyService.selectATenantkeyById(Long.valueOf(keyId));
            if (key == null) {
                return AjaxResult.error("钥匙不存在");
            }

            // 检查是否在有效期内
            Date now = new Date();
            if (now.before(key.getStartTime()) || now.after(key.getEndTime())) {
                return AjaxResult.error("钥匙不在有效期内");
            }

            // 检查是否有pwdId
            if (key.getPwdId() == null) {
                return AjaxResult.error("新增时候密码还没生效不可以修改");
            }

            // 检查钥匙状态
            if (key.getIsItAvailable() != null && key.getIsItAvailable() == 1) {
                return AjaxResult.error("钥匙已被冻结");
            }

            // 检查新密码是否已存在
            ATenantkey checkKey = new ATenantkey();
            checkKey.setMac(key.getMac());
            checkKey.setPassword(newPassword);
            List<ATenantkey> existingKeys = aTenantkeyService.selectATenantkeyList3(checkKey);
            if (!existingKeys.isEmpty()) {
                return AjaxResult.error("该密码已被使用，请更换其他密码");
            }

            // 更新钥匙密码
            ATenantkey updateKey = new ATenantkey();
            updateKey.setId(Long.valueOf(keyId));
            updateKey.setPassword(newPassword);
            updateKey.setStatus(0);
            int updateResult = aTenantkeyService.updateATenantkey(updateKey);

            if (updateResult > 0) {
                // 构建任务数据
                JSONObject data = new JSONObject();
                data.put("method", "modifyPwd");
                data.put("pwdId", key.getPwdId());
                data.put("pwd", Integer.parseInt(newPassword));
                data.put("start", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, key.getStartTime()));
                data.put("end", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, key.getEndTime()));

                // 创建任务
                ATask task = new ATask();
                task.setData(data.toString());
                task.setTarId(Long.valueOf(keyId));
                task.setTarTable("a_key");
                task.setDid(key.getMac());
                task.setType("modifyPwd");
                int taskResult = taskMapper.insertATask(task);

                if (taskResult > 0) {
                    return AjaxResult.success("密码修改成功，任务已创建");
                } else {
                    return AjaxResult.error("密码修改成功，但任务创建失败");
                }
            } else {
                return AjaxResult.error("密码修改失败");
            }

        } catch (Exception e) {
            log.error("修改钥匙密码失败", e);
            return AjaxResult.error("修改钥匙密码失败：" + e.getMessage());
        }
    }

    /**
     * 新增租户信息
     */
    @Anonymous
    @PostMapping("/user/add")
    public AjaxResult addTenantUser(@RequestBody ATenantuser aTenantuser) {
        try {
            // 设置默认值
            aTenantuser.setIsFlag("1");
            
            // 验证必填字段
            if (StringUtils.isEmpty(aTenantuser.getName())) {
                return AjaxResult.error("姓名不能为空");
            }
            if (StringUtils.isEmpty(aTenantuser.getPhone())) {
                return AjaxResult.error("手机号不能为空");
            }
            if (StringUtils.isEmpty(aTenantuser.getIdCardNumber())) {
                return AjaxResult.error("身份证号不能为空");
            }
            
            // 检查手机号是否已存在
            ATenantuser query = new ATenantuser();
            query.setPhone(aTenantuser.getPhone());
            List<ATenantuser> existingUsers = tenantuserMapper.selectATenantuserList(query);
            if (!existingUsers.isEmpty()) {
                return AjaxResult.error("该手机号已被注册");
            }
            
            // 检查身份证号是否已存在
            query = new ATenantuser();
            query.setIdCardNumber(aTenantuser.getIdCardNumber());
            existingUsers = tenantuserMapper.selectATenantuserList(query);
            if (!existingUsers.isEmpty()) {
                return AjaxResult.error("该身份证号已被注册");
            }
            aTenantuser.setCreateTime(new Date());
            // 插入新用户
            int result = tenantuserMapper.insertATenantuser(aTenantuser);
            if (result > 0) {
                return AjaxResult.success("新增租户成功", aTenantuser);
            } else {
                return AjaxResult.error("新增租户失败");
            }
        } catch (Exception e) {
            log.error("新增租户失败", e);
            return AjaxResult.error("新增租户失败：" + e.getMessage());
        }
    }

    /**
     * 文件上传接口
     */
    @Anonymous
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 检查文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return AjaxResult.error("文件大小不能超过5MB");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!Arrays.asList(".jpg", ".jpeg", ".png", ".gif").contains(suffix.toLowerCase())) {
                return AjaxResult.error("只支持jpg、jpeg、png、gif格式的图片");
            }

            // 上传到腾讯云COS
            String url = TencentCosUtils.upload(file);
            
            if (url != null) {
                return AjaxResult.success("上传成功", new HashMap<String, String>() {{
                    put("url", url);
                    put("fileName", originalFilename);
                }});
            } else {
                return AjaxResult.error("上传失败");
            }
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取系统设置信息
     */
    @Anonymous
    @GetMapping("/setting")
    public AjaxResult getSetting(@RequestAttribute("userInfo") Map<String, Object> userInfo) {
        try {
            // 从请求头获取小区ID
            if (!userInfo.containsKey("cellId") || userInfo.get("cellId") == null) {
                return AjaxResult.error("未找到小区信息");
            }
            Long cellId = Long.valueOf(userInfo.get("cellId").toString());
            
            // 通过小区ID查询系统设置
            SysSetting sysSetting = sysSettingService.selectSysSettingByCellId(cellId);
            if (sysSetting != null) {
                return AjaxResult.success(sysSetting);
            } else {
                return AjaxResult.error("未找到系统设置信息");
            }
        } catch (Exception e) {
            log.error("获取系统设置信息失败", e);
            return AjaxResult.error("获取系统设置信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取常见问题列表
     *
     * @param typeId 型号ID（可选）
     * @return 常见问题列表
     */
    @Anonymous
    @GetMapping("/problems")
    public AjaxResult getProblems(@RequestParam(required = false) String typeId) {
        try {
            AProblems query = new AProblems();
            if (typeId != null) {
                query.setTypeId(Long.valueOf(typeId));
            }
            List<AProblems> problems = problemsService.selectAProblemsList(query);
            
            if (problems != null && !problems.isEmpty()) {
                return AjaxResult.success(problems);
            } else {
                return AjaxResult.success(new ArrayList<>());
            }
        } catch (Exception e) {
            log.error("获取常见问题失败", e);
            return AjaxResult.error("获取常见问题失败：" + e.getMessage());
        }
    }

    /**
     * 获取常见问题详情
     *
     * @param id 问题ID
     * @return 问题详情
     */
    @Anonymous
    @GetMapping("/problems/{id}")
    public AjaxResult getProblemDetail(@PathVariable("id") Long id) {
        try {
            AProblems problem = problemsService.selectAProblemsById(id);
            if (problem != null) {
                return AjaxResult.success(problem);
            } else {
                return AjaxResult.error("未找到该问题");
            }
        } catch (Exception e) {
            log.error("获取问题详情失败", e);
            return AjaxResult.error("获取问题详情失败：" + e.getMessage());
        }
    }

} 